#include "musiclist.h"

#include <QStringList>
#include <QMimeDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

MusicList::MusicList()
{

}

QList<QUrl> MusicList::addMusicsByUrl(const QList<QUrl> &musicUrls)
{
    // 将所有的音乐放到musicList中
    QList<QUrl> validUrls;
    for (auto url : musicUrls)
    {
        // 过滤重复文件，如果歌曲已经在musicList中，就不再添加，直接跳过
        if (musicIndex.count(url)) continue;

        // 检测文件的MIME类型，如果url是一个有效的歌曲文件，再将其添加到歌曲列表中
        QMimeDatabase mimeDB;
        QMimeType mimeType = mimeDB.mimeTypeForFile(url.toLocalFile());
        QString mime = mimeType.name();

        if (mime == "audio/mpeg" || mime == "audio/flac" || mime == "audio/wav")
        {
//            qDebug() << mime << ": " << url;

            // 需要将url创建一个Music对象，添加到musicList中
            validUrls.push_back(url);
            Music music(url);
            musicList.push_back(music);
            musicIndex[url] = musicList.size() - 1;
        }
    }
    return validUrls;
}

iterator MusicList::findMusicByMusicUrl(const QUrl &musicUrl)
{
    if (musicIndex.count(musicUrl))
    {
        return begin() + musicIndex[musicUrl];
    }
    return end();
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

reverse_iterator MusicList::rbegin()
{
    return musicList.rbegin();
}

reverse_iterator MusicList::rend()
{
    return musicList.rend();
}

void MusicList::readFromDB()
{
    QSqlQuery query;
    query.prepare("SELECT musicId, musicName, musicSinger, albumName, musicUrl, duration, isLike, isHistory, coverImage FROM MusicInfo;");
    if (!query.exec())
    {
        qDebug() << "数据库查询失败" << query.lastError().text();
        return;
    }

    while (query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbum(query.value(3).toString());
        music.setMusicUrl("file:///" + query.value(4).toString());
        music.setDuration(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        QByteArray imageData = query.value(8).toByteArray();
        music.setCoverImage(imageData);
        musicList.push_back(music);

        // 恢复musicPaths，防止歌曲重复加载
        musicIndex[music.getMusicUrl()] = musicList.size() - 1;
    }
}

void MusicList::writeToDB()
{
    for (auto music : musicList)
    {
        // 拿到Music对象，将所有属性写入数据库
        music.insertMusicToDB();
    }
}
